using System;
using TMPro;
using Unity.VisualScripting;
using UnityEngine;
public class MousePlacer : MonoBehaviour
{
    [Header("射线设置")]
    [Tooltip("射线最大检测距离（单位：米）")]
    public float maxDistance = 100f;

    [Tooltip("射线可检测的层级")]
    public LayerMask detectionLayers = ~0; // 默认检测所有层


    [Tooltip("主相机")]
    public Camera mainCamera;

    [Header("建造器")]
    public Builder builder;

    [Header("UI引用")]
    public TextMeshProUGUI tryCountText;


    private int _tryCount = 0;

    private GameObject _currBuildingPart;
    private String _currBuildingPartName;
    public LayerMask groundLayer;
    public float heightOffset;

    private void Start()
    {

        if (mainCamera == null)
        {
            mainCamera = GameObject.Find("Main Camera").GetComponent<Camera>();
        }
        if (builder == null)
        {
            builder = GameObject.Find("Builder").GetComponent<Builder>();
        }
        ResetTryCount();
    }

    private void Update()
    {
        HandleMouseClick();
        HandleMouseMove();
    }

    private void HandleMouseMove()
    {
        if (_currBuildingPart == null) return;

        Ray ray = mainCamera.ScreenPointToRay(Input.mousePosition);

        if (Physics.Raycast(ray, out RaycastHit hit, maxDistance, groundLayer))
        {
            Vector3 targetPos = hit.point + Vector3.up * heightOffset;
            _currBuildingPart.transform.position = targetPos;
        }
    }

    private void HandleMouseClick()
    {
        if (!Input.GetMouseButtonDown(0)) return;


        // 生成射线
        Ray ray = mainCamera.ScreenPointToRay(Input.mousePosition);

        // 执行射线检测
        if (Physics.Raycast(ray, out RaycastHit hit, maxDistance, detectionLayers))
        {
            ProcessHit(hit);
        }
    }

    public void setCurrentBuildingPart(GameObject part)
    {
        if (_currBuildingPart)
        {
            _currBuildingPart.transform.position = new Vector3(100, 0, 0);
        }
        _currBuildingPart = part;
        int lastIndex = part.name.LastIndexOf('_');
        _currBuildingPartName = lastIndex >= 0 ? part.name.Substring(0, lastIndex) : part.name;
    }

    private void ProcessHit(RaycastHit hit)
    {
        GameObject clickedObject = hit.collider.gameObject;

        if (clickedObject.name.Contains("_location") && _currBuildingPart)
        { // 如果点击的是“_location”对象，则增加尝试次数
            AddTryCount();
        }

        // 调试信息
        Debug.Log($"点击对象: {clickedObject.name}\n" +
                 $"位置: {hit.point}\n" +
                 $"法线: {hit.normal}");

        if (_currBuildingPart && isLocationRight(clickedObject))
        {
            Debug.Log($"点击位置正确！");
            builder.BuildPart(_currBuildingPartName);
            _currBuildingPart.transform.position = new Vector3(100, 0, 0);
            _currBuildingPart = null;

        }

        // 示例：改变被点击物体颜色
        if (clickedObject.TryGetComponent<Renderer>(out var renderer))
        {
            StartCoroutine(FlashMaterial(renderer));
        }
    }

    // 判断该点击的位置是否是正确的放置位置
    private bool isLocationRight(GameObject clickedObject)
    {
        if (_currBuildingPart == null)
            return false;
        else
            return clickedObject.name == _currBuildingPartName + "_location";
    }

    // 协程实现闪烁效果（可选）
    private System.Collections.IEnumerator FlashMaterial(Renderer targetRenderer)
    {
        Color originalColor = targetRenderer.material.color;
        targetRenderer.material.color = Color.red;
        yield return new WaitForSeconds(0.1f);
        targetRenderer.material.color = originalColor;
    }

    // 可视化调试射线（在Scene视图中可见）
    private void OnDrawGizmos()
    {
        if (!Application.isPlaying || mainCamera == null) return;

        Gizmos.color = Color.cyan;
        Vector3 mousePos = Input.mousePosition;
        Ray ray = mainCamera.ScreenPointToRay(mousePos);
        Gizmos.DrawLine(ray.origin, ray.origin + ray.direction * maxDistance);
    }

    public void ResetTryCount()
    {
        _tryCount = 0;
        tryCountText.text = _tryCount.ToString();
    }

    private void AddTryCount()
    {
        _tryCount++;
        tryCountText.text = _tryCount.ToString();
    }
}